package juc.aqs.customelock;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 测试自定义实现 AQS.
 * 实现 不可重入锁
 * 实现 可重入锁
 *
 * @author hck
 */
public class TestCustomLock {
    public static void main(String[] args) {

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue());
        CustomLock lock = new CustomLock();
        threadPoolExecutor.submit(() -> {
            lock.lock();
            System.out.println("thread 1 lock");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
                System.out.println("thread 1 unlock");
            }
        });

        threadPoolExecutor.submit(() -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.lock();
            System.out.println("thread 2 lock");
            lock.unlock();
            System.out.println("thread 2 unlock");
        });

        threadPoolExecutor.submit(() -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.lock();
            System.out.println("thread 3 lock");
            lock.unlock();
            System.out.println("thread 3 unlock");
        });

        threadPoolExecutor.shutdown();
    }
}
